/**
 *  @author 谭
 *  用户处理函数
 */
"use strict";

const db = require('../../db/index');

const returnData = require('../../utils/returnData');

const bcyptjs = require('bcryptjs')

const jwt = require('jsonwebtoken')

const secret = require('../../schema/secret')

/*
    用户注册
 */
exports.userRegister = (req,res) => {
    try {
        let time = new Date();
        let password = bcyptjs.hashSync(req.body.password,10);
        req.body.sex = parseInt(req.body.sex);
        const sql = 'insert into user set accounts=?,password=?,school=?,sex=?,class=?,time=?';
        db.query(sql,[req.body.accounts,password,req.body.school,req.body.sex,req.body.class,time],(err,result) => {
            if (err) return returnData(res,500,err);
            if (result.affectedRows !== 1)  return returnData(res,500,'错误异常');
            return returnData(res,200,'注册成功');
        })
    } catch (e) {
        return returnData(res,500,'错误异常');
    }
}


/*
    用户登陆
 */
exports.userLogin = (req,res) => {
    try {
        const sql = 'select * from user where accounts=?';
        db.query(sql,[req.body.accounts],(err,result) => {
            if (err) return returnData(res,500,err);
            if (result.length !== 1) return returnData(res,400,'用户名或密码错误');
            let passwordResult = bcyptjs.compareSync(req.body.password,result[0].password);
            if (!passwordResult)    return returnData(res,400,'用户名或密码错误');
            let data = {
                school: result[0].school,
                sex:    result[0].sex,
                class:  result[0].class
            }
            returnData(res,200,'登陆成功',{data: data,token: 'Bearer ' + jwt.sign({accounts: result[0].accounts},secret,{expiresIn: '100000h'})});
        });
    } catch (e) {
        return returnData(res,500,'错误异常');
    }
}
